package com.wsq.demo01.service;

import com.wsq.demo01.mapper.StudentMapper;
import com.wsq.demo01.pojo.StudentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TestService {
    private StudentMapper studentMapper;

    @Autowired
    public void setStudentMapper(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取用户策略:先从缓存中获取，没有则读mysql数据，再将数据写入缓存
     */
    public StudentInfo findUserById(int id) {
        String key = "user_" + id;
        ValueOperations<String, StudentInfo> operations = redisTemplate.opsForValue();
        //判断redis中是否有键为key的缓存
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            StudentInfo studentInfo = operations.get(key);
            System.out.println("从缓存中获取数据:" + studentInfo.getName());
            System.out.println("-----------------------------");
            return studentInfo;
        } else {
            StudentInfo studentInfo = studentMapper.findUserById(id);
            System.out.println("查询数据库获取数据:" + studentInfo.getName());
            System.out.println("------------写入缓存---------------------");
            //写入缓存
            operations.set(key, studentInfo, 5, TimeUnit.HOURS);
            return studentInfo;
        }
    }

    public StudentInfo findUserByName(String name) {
        String key = "user_" + name;
        ValueOperations<String, StudentInfo> operations = redisTemplate.opsForValue();
        //判断redis中是否有键为key的缓存
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            StudentInfo studentInfo = operations.get(key);
            System.out.println("从缓存中获取数据:" + studentInfo.getName());
            System.out.println("-----------------------------");
            return studentInfo;
        } else {
            StudentInfo studentInfo = studentMapper.findUserByName(name);
            System.out.println("查询数据库获取数据:" + studentInfo.getName());
            System.out.println("------------写入缓存---------------------");
            //写入缓存
            operations.set(key, studentInfo, 5, TimeUnit.HOURS);
            return studentInfo;
        }
    }

}
